/*
 * @Description: 用户模块
 * @Autor: 人生
 * @Date: 2020-09-27 14:46:06
 * @,@LastEditors: ,: 人生
 */
import http from "@/utils/request";
const request = http.request;
import { ACCESS_TOKEN } from "@/store/mutation-types";
import storage from "store";
const recursiveTree = list => {
  let permissions = [];
  if (!list || list.length === 0) return;
  for (let i = 0; i < list.length; i++) {
    list.push(...(list[i].sonPermissionList || []))
    permissions.push(list[i].name)
  }
  return permissions
};
export default {
  state: {
    hasPermission: false, //是否有权限，登陆后设置为true
    roles: [],
    token: "",
    Userinfo: {} //用户信息
  },
  mutations: {
    SET_ROLES(state, roles) {
      state.roles = roles;
    },
    SET_INFO(state, info) {
      state.Userinfo = info;
    },
    SET_TOKEN(state, token) {
      state.token = token;
    }
  },
  actions: {
    // 获取用户信息
    GetInfo({ commit }) {
      return new Promise((resolve, reject) => {
        request({
          url: "/manager/info",
          method: "get"
        })
          .then(res => {
            const result = res.data;
            if (result.permissionList && result.permissionList.length > 0) {
              //将权限数组打平
              result.roles = recursiveTree(result.permissionList)
              commit("SET_ROLES", result.roles || []);
              commit("SET_INFO", result);
              resolve(result);
            } else {
              reject(new Error("/manager/info: 没有返回用户的权限相关字段!"));
            }
          })
          .catch(error => {
            console.log("error", error);
          });
      });
    },
    // 登录
    Login({ commit }, userInfo) {
      return new Promise((resolve, reject) => {
        request({
          url: "/login/manager",
          method: "post",
          data: userInfo
        })
          .then(res => {
            const data = res.data;
            storage.set(ACCESS_TOKEN, data.token, 7 * 24 * 60 * 60 * 1000);
            commit("SET_TOKEN", data.token);
            resolve();
          })
          .catch(error => {
            reject(error);
          });
      });
    },

    // 登出
    Logout({ commit, state }) {
      return new Promise(resolve => {
        request({
          url: "/login/manager/logout",
          method: "delete",
          params: { token: state.token }
        })
          .then(() => {
            commit("SET_TOKEN", "");
            commit("SET_ROLES", []);
            storage.remove(ACCESS_TOKEN);
            resolve();
          })
          .catch(() => {
            resolve();
          })
          .finally(() => {});
      });
    }
  }
};
